<template>
  <div class="log-monitor-container">
    <el-card class="header-card">
      <template #header>
        <div class="card-header">
          <h2>敏感操作日志监控</h2>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>刷新数据
            </el-button>
            <el-button type="danger" @click="showCleanDialog">
              <el-icon><Delete /></el-icon>清理日志
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 统计卡片区域 -->
      <div class="stat-cards" v-loading="statisticsLoading">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-info">
              <h3>今日操作</h3>
              <div class="stat-number">{{ statistics.todayCount || 0 }}</div>
            </div>
            <div class="stat-icon today">
              <el-icon><Calendar /></el-icon>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-info">
              <h3>本周操作</h3>
              <div class="stat-number">{{ statistics.weekCount || 0 }}</div>
            </div>
            <div class="stat-icon week">
              <el-icon><TrendCharts /></el-icon>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-info">
              <h3>本月操作</h3>
              <div class="stat-number">{{ statistics.monthCount || 0 }}</div>
            </div>
            <div class="stat-icon month">
              <el-icon><DataAnalysis /></el-icon>
            </div>
          </div>
        </el-card>
        
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-info">
              <h3>总计操作</h3>
              <div class="stat-number">{{ statistics.totalCount || 0 }}</div>
            </div>
            <div class="stat-icon total">
              <el-icon><DataLine /></el-icon>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>
    
    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <div class="filter-row">
        <div class="filter-left">
          <el-select
            v-model="queryForm.operationType"
            placeholder="请选择操作类型"
            clearable
            style="width: 150px; margin-right: 10px;"
          >
            <el-option label="删除操作" value="删除操作" />
            <el-option label="修改操作" value="修改操作" />
            <el-option label="重置操作" value="重置操作" />
            <el-option label="批量操作" value="批量操作" />
          </el-select>
          
          <el-input
            v-model="queryForm.operatorUsername"
            placeholder="搜索操作人用户名"
            clearable
            style="width: 200px; margin-right: 10px;"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
          
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px; margin-right: 10px;"
          />
        </div>
        
        <div class="filter-right">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshRight /></el-icon>重置
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 日志列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <h3>敏感操作日志</h3>
          <div class="list-actions">
            <span class="total-count">共 {{ total }} 条记录</span>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="logList" 
        v-loading="loading"
        stripe
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="operationType" label="操作类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getOperationTypeTag(scope.row.operationType)" size="small">
              {{ scope.row.operationType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationDesc" label="操作描述" min-width="200" />
        <el-table-column prop="operatorUsername" label="操作人" width="150" align="center">
          <template #default="scope">
            <div class="operator-info">
              <el-icon><User /></el-icon>
              <div class="operator-details">
                <div class="operator-name">{{ scope.row.operatorUsername }}</div>
                <div class="operator-id">ID: {{ scope.row.operatorId }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="operationTime" label="操作时间" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.operationTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" link @click.stop="viewDetail(scope.row)">
              <el-icon><View /></el-icon>详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 空状态 -->
      <div class="empty-placeholder" v-if="logList.length === 0 && !loading">
        <el-empty description="暂无敏感操作日志" />
      </div>
    </el-card>
    
    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="600px"
      destroy-on-close
    >
      <div class="detail-content" v-if="selectedLog">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="日志ID">{{ selectedLog.id }}</el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getOperationTypeTag(selectedLog.operationType)" size="small">
              {{ selectedLog.operationType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作描述">{{ selectedLog.operationDesc }}</el-descriptions-item>
          <el-descriptions-item label="操作人ID">{{ selectedLog.operatorId }}</el-descriptions-item>
          <el-descriptions-item label="操作人用户名">{{ selectedLog.operatorUsername }}</el-descriptions-item>
          <el-descriptions-item label="操作时间">
            {{ formatDateTime(selectedLog.operationTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(selectedLog.createdAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
    
    <!-- 清理日志对话框 -->
    <el-dialog
      v-model="cleanDialogVisible"
      title="清理日志"
      width="500px"
    >
      <div class="clean-content">
        <el-alert
          title="警告"
          type="warning"
          description="清理操作将永久删除指定天数之前的日志记录，请谨慎操作！"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <el-form :model="cleanForm" label-width="100px">
          <el-form-item label="保留天数">
            <el-input-number
              v-model="cleanForm.days"
              :min="1"
              :max="365"
              placeholder="请输入保留天数"
              style="width: 200px;"
            />
            <div class="form-help">删除 {{ cleanForm.days }} 天之前的日志记录</div>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmClean" :loading="cleanLoading">
            确认清理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Delete,
  Calendar,
  TrendCharts,
  DataAnalysis,
  DataLine,
  User,
  Search,
  RefreshRight,
  View
} from '@element-plus/icons-vue'
import { 
  sensitiveLogApi, 
  type SensitiveLog, 
  type SensitiveLogQuery,
  type SensitiveLogStatistics
} from '@/api/sensitiveLog'

// 响应式数据
const loading = ref(false)
const statisticsLoading = ref(false)
const cleanLoading = ref(false)
const logList = ref<SensitiveLog[]>([])
const total = ref(0)
const statistics = ref<SensitiveLogStatistics>({
  todayCount: 0,
  weekCount: 0,
  monthCount: 0,
  totalCount: 0
})

// 查询表单
const queryForm = reactive<SensitiveLogQuery>({
  pageNum: 1,
  pageSize: 20,
  operationType: '',
  operatorUsername: '',
  startTime: '',
  endTime: ''
})

// 时间范围
const timeRange = ref<[string, string] | null>(null)

// 对话框相关
const detailDialogVisible = ref(false)
const cleanDialogVisible = ref(false)
const selectedLog = ref<SensitiveLog | null>(null)

// 清理表单
const cleanForm = reactive({
  days: 30
})

// 获取统计数据
const getStatistics = async () => {
  try {
    statisticsLoading.value = true
    const response = await sensitiveLogApi.getSensitiveLogStatistics()
    
    if (response.code === 200) {
      statistics.value = response.data
    } else {
      ElMessage.error(response.msg || '获取统计数据失败')
    }
  } catch (error: any) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    statisticsLoading.value = false
  }
}

// 获取日志列表
const getLogList = async () => {
  try {
    loading.value = true
    
    // 处理时间范围
    if (timeRange.value) {
      queryForm.startTime = timeRange.value[0]
      queryForm.endTime = timeRange.value[1]
    } else {
      queryForm.startTime = ''
      queryForm.endTime = ''
    }
    
    const response = await sensitiveLogApi.getSensitiveLogs(queryForm)
    
    if (response.code === 200) {
      logList.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取日志列表失败')
      logList.value = []
      total.value = 0
    }
  } catch (error: any) {
    console.error('获取日志列表失败:', error)
    ElMessage.error('获取日志列表失败')
    logList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = async () => {
  await Promise.all([getStatistics(), getLogList()])
}

// 搜索
const handleSearch = () => {
  queryForm.pageNum = 1
  getLogList()
}

// 重置
const handleReset = () => {
  queryForm.pageNum = 1
  queryForm.pageSize = 20
  queryForm.operationType = ''
  queryForm.operatorUsername = ''
  timeRange.value = null
  getLogList()
}

// 分页处理
const handleSizeChange = (val: number) => {
  queryForm.pageSize = val
  queryForm.pageNum = 1
  getLogList()
}

const handleCurrentChange = (val: number) => {
  queryForm.pageNum = val
  getLogList()
}

// 查看详情
const viewDetail = async (log: SensitiveLog) => {
  try {
    const response = await sensitiveLogApi.getSensitiveLogDetail(log.id)
    
    if (response.code === 200) {
      selectedLog.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取日志详情失败')
    }
  } catch (error: any) {
    console.error('获取日志详情失败:', error)
    ElMessage.error('获取日志详情失败')
  }
}

// 行点击事件
const handleRowClick = (row: SensitiveLog) => {
  viewDetail(row)
}

// 显示清理对话框
const showCleanDialog = () => {
  cleanDialogVisible.value = true
}

// 确认清理
const confirmClean = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清理 ${cleanForm.days} 天之前的日志记录吗？此操作不可撤销！`,
      '确认清理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    cleanLoading.value = true
    const response = await sensitiveLogApi.cleanSensitiveLogs(cleanForm.days)
    
    if (response.code === 200) {
      ElMessage.success(response.data || '清理完成')
      cleanDialogVisible.value = false
      // 刷新数据
      refreshData()
    } else {
      ElMessage.error(response.msg || '清理失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('清理日志失败:', error)
      ElMessage.error('清理日志失败')
    }
  } finally {
    cleanLoading.value = false
  }
}

// 获取操作类型标签颜色
const getOperationTypeTag = (type: string) => {
  const typeMap: { [key: string]: string } = {
    '删除操作': 'danger',
    '修改操作': 'warning',
    '重置操作': 'info',
    '批量操作': 'success'
  }
  return typeMap[type] || 'default'
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.log-monitor-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.stat-card {
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-info h3 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.today {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.week {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.month {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.total {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.filter-card {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-left {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-right {
  display: flex;
  gap: 10px;
}

.list-card {
  margin-bottom: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.total-count {
  color: #666;
  font-size: 14px;
}

.operator-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.operator-details {
  text-align: center;
}

.operator-name {
  font-weight: 500;
  color: #333;
}

.operator-id {
  font-size: 12px;
  color: #999;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.empty-placeholder {
  margin: 40px 0;
}

.detail-content {
  padding: 10px 0;
}

.clean-content {
  padding: 10px 0;
}

.form-help {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

@media (max-width: 1200px) {
  .stat-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .stat-cards {
    grid-template-columns: 1fr;
  }
  
  .filter-left {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-right {
    justify-content: flex-start;
  }
}
</style> 